from django.db import models
from django_cryptography.fields import encrypt
import uuid


class City(models.Model):
    name = models.CharField(max_length=100, unique=True)
    code = models.CharField(max_length=10, unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class IDC(models.Model):
    name = models.CharField(max_length=100)
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    address = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('name', 'city')

    def __str__(self):
        return f"{self.name} ({self.city})"


class Host(models.Model):
    STATUS_CHOICES = [
        ('active', 'Active'),
        ('maintenance', 'Maintenance'),
        ('decommissioned', 'Decommissioned'),
    ]

    hostname = models.CharField(max_length=100, unique=True)
    ip_address = models.GenericIPAddressField(protocol='IPv4', unique=True)
    idc = models.ForeignKey(IDC, on_delete=models.CASCADE)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    root_password = encrypt(models.CharField(max_length=128))
    last_password_change = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.hostname} ({self.ip_address})"


class HostStat(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    idc = models.ForeignKey(IDC, on_delete=models.CASCADE)
    host_count = models.PositiveIntegerField(default=0)
    stat_date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ('city', 'idc', 'stat_date')
        indexes = [
            models.Index(fields=['stat_date']),
        ]

    def __str__(self):
        return f"{self.city}-{self.idc} ({self.stat_date}): {self.host_count}"


class RequestLog(models.Model):
    request_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    path = models.CharField(max_length=255)
    method = models.CharField(max_length=10)
    duration = models.FloatField(help_text="Request duration in seconds")
    status_code = models.PositiveIntegerField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.method} {self.path} - {self.duration:.3f}s"
